<!DOCTYPE html>


<html lang="zh-CN">


<head>
  <meta charset="utf-8" />
   
  <meta name="keywords" content="zesicus" />
   
  <meta name="description" content="有所感，有所记" />
  
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    EMA策略回测问题2020.06.21 |  黑森林
  </title>
  <meta name="generator" content="hexo-theme-ayer">
  
  <link rel="shortcut icon" href="/images/littleicon.png" />
  
  
<link rel="stylesheet" href="/dist/main.css">

  
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css">

  
<link rel="stylesheet" href="/css/custom.css">

  
  
<script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>

  
  

  

<link rel="alternate" href="/atom.xml" title="黑森林" type="application/atom+xml">
</head>

</html>

<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-EMA策略回测问题2020-06-21"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  EMA策略回测问题2020.06.21
</h1>
 

    </header>
     
    <div class="article-meta">
      <a href="/2021/06/21/EMA%E7%AD%96%E7%95%A5%E5%9B%9E%E6%B5%8B%E9%97%AE%E9%A2%982020-06-21/" class="article-date">
  <time datetime="2021-06-21T04:13:50.000Z" itemprop="datePublished">2021-06-21</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/%E9%87%8F%E5%8C%96/">量化</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">3.2k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">15 分钟</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <h3 id="问题描述"><a href="#问题描述" class="headerlink" title="问题描述"></a>问题描述</h3><p>下载 OKEX 的 TRX 最近半年的交易数据，跑简单的 EMA 策略，仅保留金叉买，死叉卖的逻辑。但是回测发现分析结果 Balance 一路下跌，但是自己对 <code>on_trade</code> 打印日志，应该是有所收益才对。</p>
<p>针对的代码和回测结果，我有两个问题：</p>
<p><strong>1. 在 <code>on_xxx_bar</code> 里进行 <code>send_order</code> 操作，连续几单都是买或卖，为什么 <code>on_trade</code> 只打印出交易的最后一单而不是第一单。</strong></p>
<p>问题1日志:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">Sell:</span><br><span class="line">满仓，遇到死叉，将卖出 TRX：3758.465011286682</span><br><span class="line">发送卖出订单，订单 id: [&#39;BACKTESTING.2&#39;]</span><br><span class="line">------------------------------------------------------------------</span><br><span class="line">Sell:</span><br><span class="line">满仓，遇到死叉，将卖出 TRX：3758.465011286682</span><br><span class="line">发送卖出订单，订单 id: [&#39;BACKTESTING.3&#39;]</span><br><span class="line">------------------------------------------------------------------</span><br><span class="line">Sell:</span><br><span class="line">满仓，遇到死叉，将卖出 TRX：3758.465011286682</span><br><span class="line">发送卖出订单，订单 id: [&#39;BACKTESTING.4&#39;]</span><br><span class="line">------------------------------------------------------------------</span><br><span class="line">Sell:</span><br><span class="line">满仓，遇到死叉，将卖出 TRX：3758.465011286682</span><br><span class="line">发送卖出订单，订单 id: [&#39;BACKTESTING.5&#39;]</span><br><span class="line">------------------------------------------------------------------</span><br><span class="line">TradeData(gateway_name&#x3D;&#39;BACKTESTING&#39;, symbol&#x3D;&#39;TRX-USDT&#39;, exchange&#x3D;&lt;Exchange.OKEX: &#39;OKEX&#39;&gt;, orderid&#x3D;&#39;5&#39;, tradeid&#x3D;&#39;2&#39;, direction&#x3D;&lt;Direction.SHORT: &#39;空&#39;&gt;, offset&#x3D;&lt;Offset.CLOSE: &#39;平&#39;&gt;, price&#x3D;0.02911, volume&#x3D;3758.465011286682, datetime&#x3D;datetime.datetime(2020, 12, 29, 10, 30, tzinfo&#x3D;&lt;DstTzInfo &#39;Asia&#x2F;Shanghai&#39; LMT+8:06:00 STD&gt;))</span><br><span class="line">当前剩余 USDT：109.5089164785553, TRX：0.0</span><br></pre></td></tr></table></figure>
<p><strong>2. 为什么计算的策略统计指标的收益和我通过 <code>on_trade</code> 打印出来的收益不同。</strong></p>
<p>体现在自己的打印日志“当前剩余 433”和策略指标计算的“结束资金 -170”差距大相径庭：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br></pre></td><td class="code"><pre><span class="line">2021-06-21 12:14:57.937366	开始加载历史数据</span><br><span class="line">2021-06-21 12:15:00.051435	加载进度：# [17%]</span><br><span class="line">2021-06-21 12:15:02.240418	加载进度：### [33%]</span><br><span class="line">2021-06-21 12:15:04.470956	加载进度：##### [50%]</span><br><span class="line">2021-06-21 12:15:06.711540	加载进度：###### [67%]</span><br><span class="line">2021-06-21 12:15:09.028636	加载进度：######## [83%]</span><br><span class="line">2021-06-21 12:15:11.427844	加载进度：######### [100%]</span><br><span class="line">2021-06-21 12:15:11.427883	历史数据加载完成，数据量：259097</span><br><span class="line">2021-06-21 12:15:11.434531	策略初始化完成</span><br><span class="line">2021-06-21 12:15:11.434544	开始回放历史数据</span><br><span class="line">Buy:</span><br><span class="line">空仓，遇到金叉，持有 USDT：100, 将买入 TRX：3762.227238525207</span><br><span class="line">发送买入订单，订单 id: [&#39;BACKTESTING.1&#39;]</span><br><span class="line">------------------------------------------------------------------</span><br><span class="line">TradeData(gateway_name&#x3D;&#39;BACKTESTING&#39;, symbol&#x3D;&#39;TRX-USDT&#39;, exchange&#x3D;&lt;Exchange.OKEX: &#39;OKEX&#39;&gt;, orderid&#x3D;&#39;1&#39;, tradeid&#x3D;&#39;1&#39;, direction&#x3D;&lt;Direction.LONG: &#39;多&#39;&gt;, offset&#x3D;&lt;Offset.OPEN: &#39;开&#39;&gt;, price&#x3D;0.02658, volume&#x3D;3758.465011286682, datetime&#x3D;datetime.datetime(2020, 12, 24, 20, 30, tzinfo&#x3D;&lt;DstTzInfo &#39;Asia&#x2F;Shanghai&#39; LMT+8:06:00 STD&gt;))</span><br><span class="line">当前剩余 USDT：0.09999999999999432, TRX：3758.465011286682</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">.............</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">Sell:</span><br><span class="line">满仓，遇到死叉，将卖出 TRX：6078.647259845156</span><br><span class="line">发送卖出订单，订单 id: [&#39;BACKTESTING.198&#39;]</span><br><span class="line">------------------------------------------------------------------</span><br><span class="line">TradeData(gateway_name&#x3D;&#39;BACKTESTING&#39;, symbol&#x3D;&#39;TRX-USDT&#39;, exchange&#x3D;&lt;Exchange.OKEX: &#39;OKEX&#39;&gt;, orderid&#x3D;&#39;198&#39;, tradeid&#x3D;&#39;154&#39;, direction&#x3D;&lt;Direction.SHORT: &#39;空&#39;&gt;, offset&#x3D;&lt;Offset.CLOSE: &#39;平&#39;&gt;, price&#x3D;0.07115, volume&#x3D;6078.647259845156, datetime&#x3D;datetime.datetime(2021, 6, 16, 19, 0, tzinfo&#x3D;&lt;DstTzInfo &#39;Asia&#x2F;Shanghai&#39; LMT+8:06:00 STD&gt;))</span><br><span class="line">当前剩余 USDT：433.724868400334, TRX：0.0</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">2021-06-21 12:15:12.776025	历史数据回放结束</span><br><span class="line">2021-06-21 12:15:12.776058	开始计算逐日盯市盈亏</span><br><span class="line">2021-06-21 12:15:12.788616	逐日盯市盈亏计算完成</span><br><span class="line">2021-06-21 12:15:12.788662	开始计算策略统计指标</span><br><span class="line">&#x2F;Users&#x2F;zesicus&#x2F;opt&#x2F;anaconda3&#x2F;envs&#x2F;trade&#x2F;lib&#x2F;python3.7&#x2F;site-packages&#x2F;pandas&#x2F;core&#x2F;arraylike.py:358: RuntimeWarning: invalid value encountered in log</span><br><span class="line">  result &#x3D; getattr(ufunc, method)(*inputs, **kwargs)</span><br><span class="line">2021-06-21 12:15:12.801951	------------------------------</span><br><span class="line">2021-06-21 12:15:12.801977	首个交易日：	2020-12-21</span><br><span class="line">2021-06-21 12:15:12.801986	最后交易日：	2021-06-16</span><br><span class="line">2021-06-21 12:15:12.801992	总交易日：	178</span><br><span class="line">2021-06-21 12:15:12.801997	盈利交易日：	53</span><br><span class="line">2021-06-21 12:15:12.802002	亏损交易日：	87</span><br><span class="line">2021-06-21 12:15:12.802011	起始资金：	100.00</span><br><span class="line">2021-06-21 12:15:12.802019	结束资金：	-170.38</span><br><span class="line">2021-06-21 12:15:12.802025	总收益率：	-270.38%</span><br><span class="line">2021-06-21 12:15:12.802031	年化收益：	-554.43%</span><br><span class="line">2021-06-21 12:15:12.802036	最大回撤: 	-292.19</span><br><span class="line">2021-06-21 12:15:12.802042	百分比最大回撤: -239.87%</span><br><span class="line">2021-06-21 12:15:12.802047	最长回撤天数: 	62</span><br><span class="line">2021-06-21 12:15:12.802053	总盈亏：	-270.38</span><br><span class="line">2021-06-21 12:15:12.802058	总手续费：	40.73</span><br><span class="line">2021-06-21 12:15:12.802064	总滑点：	563.37</span><br><span class="line">2021-06-21 12:15:12.802070	总成交金额：	40,732.31</span><br><span class="line">2021-06-21 12:15:12.802076	总成交笔数：	154</span><br><span class="line">2021-06-21 12:15:12.802082	日均盈亏：	-1.52</span><br><span class="line">2021-06-21 12:15:12.802088	日均手续费：	0.23</span><br><span class="line">2021-06-21 12:15:12.802093	日均滑点：	3.17</span><br><span class="line">2021-06-21 12:15:12.802099	日均成交金额：	228.83</span><br><span class="line">2021-06-21 12:15:12.802107	日均成交笔数：	0.8651685393258427</span><br><span class="line">2021-06-21 12:15:12.802113	日均收益率：	0.29%</span><br><span class="line">2021-06-21 12:15:12.802118	收益标准差：	59.03%</span><br><span class="line">2021-06-21 12:15:12.802124	Sharpe Ratio：	0.09</span><br><span class="line">2021-06-21 12:15:12.802130	收益回撤比：	-1.13</span><br><span class="line">2021-06-21 12:15:12.802617	策略统计指标计算完成</span><br></pre></td></tr></table></figure>

<h3 id="分析解决"><a href="#分析解决" class="headerlink" title="分析解决"></a>分析解决</h3><p><strong>针对第一个问题</strong>，因为在 <code>on_xxx_bar</code> 函数里加了 <code>self.cancel_all()</code> 导致的，去掉就正常了，但是根据我的理解，既然是回测就应该不会有延迟并且应该同步执行，这个问题算解决了一半。</p>
<blockquote>
<p>猜想也许不在回测的时候，<code>on_xxx_bar</code> 回调的时间长，那么 <code>on_trade</code> 就会及时成交，也许不会出现问题，这时候 <code>self.cancel_all()</code> 也许就会适得其所。</p>
</blockquote>
<p><strong>针对第二个问题</strong>，既然不知道收益为什么是负的，那么就跟踪到策略内部计算的部分去排查作者是怎样进行计算的，计算部分是在 <code>backtesting.py</code> 文件的 <code>calculate_pnl</code> 函数里面，根据理解对计算的变量加了注释：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">calculate_pnl</span>(<span class="params"></span></span></span><br><span class="line"><span class="function"><span class="params">        self,</span></span></span><br><span class="line"><span class="function"><span class="params">        pre_close: <span class="built_in">float</span>,</span></span></span><br><span class="line"><span class="function"><span class="params">        start_pos: <span class="built_in">float</span>,</span></span></span><br><span class="line"><span class="function"><span class="params">        size: <span class="built_in">int</span>,</span></span></span><br><span class="line"><span class="function"><span class="params">        rate: <span class="built_in">float</span>,</span></span></span><br><span class="line"><span class="function"><span class="params">        slippage: <span class="built_in">float</span>,</span></span></span><br><span class="line"><span class="function"><span class="params">        inverse: <span class="built_in">bool</span></span></span></span><br><span class="line"><span class="function"><span class="params">    </span>):</span></span><br><span class="line">        <span class="string">&quot;&quot;&quot;&quot;&quot;&quot;</span></span><br><span class="line">        <span class="comment"># If no pre_close provided on the first day,</span></span><br><span class="line">        <span class="comment"># use value 1 to avoid zero division error</span></span><br><span class="line">        <span class="keyword">if</span> pre_close:</span><br><span class="line">            self.pre_close = pre_close</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            self.pre_close = <span class="number">1</span></span><br><span class="line"></span><br><span class="line">        <span class="comment"># Holding pnl is the pnl from holding position at day start</span></span><br><span class="line">        self.start_pos = start_pos</span><br><span class="line">        self.end_pos = start_pos</span><br><span class="line"></span><br><span class="line">        print(<span class="string">f&#x27;coin持有量: <span class="subst">&#123;self.start_pos&#125;</span>&#x27;</span>)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> inverse:     <span class="comment"># For normal contract</span></span><br><span class="line">            self.holding_pnl = self.start_pos * \</span><br><span class="line">                (self.close_price - self.pre_close) * size</span><br><span class="line">            print(</span><br><span class="line">                <span class="string">f&#x27;收盘时相对收益 = (原coin持有量)<span class="subst">&#123;self.start_pos&#125;</span> * ((收盘价)<span class="subst">&#123;self.close_price&#125;</span> - (之前交易价格)<span class="subst">&#123;self.pre_close&#125;</span>) * (张数)<span class="subst">&#123;size&#125;</span> = <span class="subst">&#123;self.holding_pnl&#125;</span>&#x27;</span>)</span><br><span class="line">        <span class="keyword">else</span>:               <span class="comment"># For crypto currency inverse contract</span></span><br><span class="line">            self.holding_pnl = self.start_pos * \</span><br><span class="line">                (<span class="number">1</span> / self.pre_close - <span class="number">1</span> / self.close_price) * size</span><br><span class="line"></span><br><span class="line">        <span class="comment"># Trading pnl is the pnl from new trade during the day</span></span><br><span class="line">        self.trade_count = <span class="built_in">len</span>(self.trades)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> <span class="built_in">len</span>(self.trades) &gt; <span class="number">0</span>:</span><br><span class="line">            print(<span class="string">&quot;------------------------------------------------------------&quot;</span>)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> trade <span class="keyword">in</span> self.trades:</span><br><span class="line">            <span class="keyword">if</span> trade.direction == Direction.LONG:</span><br><span class="line">                pos_change = trade.volume</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                pos_change = -trade.volume</span><br><span class="line"></span><br><span class="line">            print(<span class="string">f&#x27;coin交易量: <span class="subst">&#123;pos_change&#125;</span>&#x27;</span>)</span><br><span class="line"></span><br><span class="line">            print(<span class="string">f&#x27;coin剩余量 = (原剩余量)<span class="subst">&#123;self.end_pos&#125;</span> + (交易量)<span class="subst">&#123;pos_change&#125;</span>&#x27;</span>)</span><br><span class="line">            self.end_pos += pos_change</span><br><span class="line">            print(<span class="string">f&#x27;coin剩余量 = <span class="subst">&#123;self.end_pos&#125;</span>&#x27;</span>)</span><br><span class="line"></span><br><span class="line">            <span class="comment"># For normal contract</span></span><br><span class="line">            <span class="keyword">if</span> <span class="keyword">not</span> inverse:</span><br><span class="line">                turnover = trade.volume * size * trade.price</span><br><span class="line">                print(</span><br><span class="line">                    <span class="string">f&#x27;此次交易资产 = (coin交易量)<span class="subst">&#123;trade.volume&#125;</span> * (交易价格)<span class="subst">&#123;trade.price&#125;</span> * (合约张数)<span class="subst">&#123;size&#125;</span> = <span class="subst">&#123;turnover&#125;</span>&#x27;</span>)</span><br><span class="line">                self.trading_pnl += pos_change * \</span><br><span class="line">                    (self.close_price - trade.price) * size</span><br><span class="line">                print(</span><br><span class="line">                    <span class="string">f&#x27;此次交易预估收益 = (coin交易量)<span class="subst">&#123;pos_change&#125;</span> * ((收盘价)<span class="subst">&#123;self.close_price&#125;</span> - (交易价格)<span class="subst">&#123;trade.price&#125;</span>) * (合约张数)<span class="subst">&#123;size&#125;</span> = <span class="subst">&#123;self.trading_pnl&#125;</span>&#x27;</span>)</span><br><span class="line">                print(</span><br><span class="line">                    <span class="string">f&#x27;总滑点损失 = (总滑点损失)<span class="subst">&#123;self.slippage&#125;</span> + (coin交易量)<span class="subst">&#123;trade.volume&#125;</span> * (合约张数)<span class="subst">&#123;size&#125;</span> * (滑点)<span class="subst">&#123;slippage&#125;</span>&#x27;</span>)</span><br><span class="line">                self.slippage += trade.volume * size * slippage</span><br><span class="line">                print(<span class="string">f&#x27;总滑点损失 = <span class="subst">&#123;self.slippage&#125;</span>&#x27;</span>)</span><br><span class="line">            <span class="comment"># For crypto currency inverse contract</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                turnover = trade.volume * size / trade.price</span><br><span class="line">                self.trading_pnl += pos_change * \</span><br><span class="line">                    (<span class="number">1</span> / trade.price - <span class="number">1</span> / self.close_price) * size</span><br><span class="line">                self.slippage += trade.volume * \</span><br><span class="line">                    size * slippage / (trade.price ** <span class="number">2</span>)</span><br><span class="line"></span><br><span class="line">            print(<span class="string">f&#x27;总交易资产 = (总交易资产)<span class="subst">&#123;self.turnover&#125;</span> + (此次交易资产)<span class="subst">&#123;turnover&#125;</span>&#x27;</span>)</span><br><span class="line">            self.turnover += turnover</span><br><span class="line">            print(<span class="string">f&#x27;总交易资产 = <span class="subst">&#123;self.turnover&#125;</span>&#x27;</span>)</span><br><span class="line">            print(<span class="string">f&#x27;手续费 = <span class="subst">&#123;self.commission&#125;</span> + <span class="subst">&#123;turnover&#125;</span> * <span class="subst">&#123;rate&#125;</span>&#x27;</span>)</span><br><span class="line">            self.commission += turnover * rate</span><br><span class="line">            print(<span class="string">f&#x27;手续费 = <span class="subst">&#123;self.commission&#125;</span>&#x27;</span>)</span><br><span class="line">            print(<span class="string">&quot;------------------------------------------------------------&quot;</span>)</span><br><span class="line"></span><br><span class="line">        <span class="comment"># Net pnl takes account of commission and slippage cost</span></span><br><span class="line">        self.total_pnl = self.trading_pnl + self.holding_pnl</span><br><span class="line">        print(</span><br><span class="line">            <span class="string">f&#x27;本次总收益 = (此次交易预估收益)<span class="subst">&#123;self.trading_pnl&#125;</span> + (收盘时相对收益)<span class="subst">&#123;self.holding_pnl&#125;</span> = <span class="subst">&#123;self.total_pnl&#125;</span>&#x27;</span>)</span><br><span class="line">        self.net_pnl = self.total_pnl - self.commission - self.slippage</span><br><span class="line">        print(</span><br><span class="line">            <span class="string">f&#x27;本次净收益 = (总收益)<span class="subst">&#123;self.total_pnl&#125;</span> - (手续费)<span class="subst">&#123;self.commission&#125;</span> - (滑点损失)<span class="subst">&#123;self.slippage&#125;</span> = <span class="subst">&#123;self.net_pnl&#125;</span>&#x27;</span>)</span><br><span class="line">        print(<span class="string">&#x27;\n&#x27;</span>)</span><br></pre></td></tr></table></figure>
<p>加过注释然后重新跑一遍就清晰了，本金是 100 没错，每次都会计算 <code>self.net_pnl</code> 这个净收益，是不断累加的，所以本金累加净收益就变成负的了。</p>
<p>究其原因，导致结果差距巨大是因为 <strong>“滑点”</strong>，因为滑点的巨量损失导致交易差距巨大，另外，由于发送 <code>self.buy</code> 订单时，使用的全部资金量是自己计算得出的，也并未计算滑点，所以修改策略代码如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">on_30m_bar</span>(<span class="params">self, bar: BarData</span>):</span></span><br><span class="line">    isTrade = <span class="literal">False</span></span><br><span class="line">    <span class="comment"># 把上一小时单全部撤掉重新判断</span></span><br><span class="line">    <span class="comment"># self.cancel_all() # 注释掉这一句，能够确保每一单成交，不会遇到多个死叉或金叉成交最后一单问题</span></span><br><span class="line">    <span class="comment"># 新数据放到 am 数组中</span></span><br><span class="line">    self.am.update_bar(bar)</span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> self.am.inited:</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    <span class="comment"># TA-Lib 进行 EMA 移动均线计算</span></span><br><span class="line">    short_ema_values = talib.EMA(self.am.close_array,</span><br><span class="line">                                    timeperiod=self.short_ema_period)</span><br><span class="line">    long_ema_values = talib.EMA(</span><br><span class="line">        self.am.close_array, timeperiod=self.long_ema_period)</span><br><span class="line">    <span class="comment"># refer_ema_values = talib.EMA(</span></span><br><span class="line">    <span class="comment">#     self.am.close_array, timeperiod=self.refer_ema_period)</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 金叉，死叉进行判断</span></span><br><span class="line">    <span class="keyword">if</span> short_ema_values[-<span class="number">1</span>] &gt; long_ema_values[-<span class="number">1</span>] <span class="keyword">and</span> short_ema_values[-<span class="number">2</span>] &lt; long_ema_values[-<span class="number">2</span>]:</span><br><span class="line">        trend_status = <span class="number">1</span>  <span class="comment"># 金叉</span></span><br><span class="line">    <span class="keyword">elif</span> short_ema_values[-<span class="number">1</span>] &lt; long_ema_values[-<span class="number">1</span>] <span class="keyword">and</span> short_ema_values[-<span class="number">2</span>] &gt; long_ema_values[-<span class="number">2</span>]:</span><br><span class="line">        trend_status = -<span class="number">1</span>  <span class="comment"># 死叉</span></span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        trend_status = <span class="number">0</span>  <span class="comment"># 非金/死叉交汇时的状态</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> trend_status == <span class="number">1</span>:</span><br><span class="line">        <span class="keyword">if</span> self.trade_money &gt; <span class="number">10</span>:</span><br><span class="line">            print(<span class="string">f&#x27;Buy: <span class="subst">&#123;bar.datetime&#125;</span>&#x27;</span>)</span><br><span class="line">            print(</span><br><span class="line">                <span class="string">f&#x27;空仓，遇到金叉，持有 USDT：<span class="subst">&#123;self.trade_money&#125;</span>, 将买入 TRX：<span class="subst">&#123;self.trade_money / bar.close_price&#125;</span>&#x27;</span>)</span><br><span class="line">            buy_id = self.buy(bar.close_price, self.trade_money *</span><br><span class="line">                                (<span class="number">1</span> + trade_fee_rate) / bar.close_price)  <span class="comment"># 做多</span></span><br><span class="line">            isTrade = <span class="literal">True</span></span><br><span class="line">            print(<span class="string">f&#x27;发送买入订单，订单 id: <span class="subst">&#123;buy_id&#125;</span>&#x27;</span>)</span><br><span class="line">    <span class="keyword">elif</span> trend_status == -<span class="number">1</span>:</span><br><span class="line">        <span class="keyword">if</span> self.pos &gt; <span class="number">0</span>:</span><br><span class="line">            print(<span class="string">f&#x27;Sell: <span class="subst">&#123;bar.datetime&#125;</span>&#x27;</span>)</span><br><span class="line">            print(<span class="string">f&#x27;满仓，遇到死叉，将卖出 TRX：<span class="subst">&#123;self.pos&#125;</span>&#x27;</span>)</span><br><span class="line">            sell_id = self.sell(</span><br><span class="line">                bar.close_price * (<span class="number">1</span> - trade_fee_rate), self.pos)  <span class="comment"># 先平仓</span></span><br><span class="line">            isTrade = <span class="literal">True</span></span><br><span class="line">            print(<span class="string">f&#x27;发送卖出订单，订单 id: <span class="subst">&#123;sell_id&#125;</span>&#x27;</span>)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> isTrade:</span><br><span class="line">        print(<span class="string">&#x27;------------------------------------------------------------------&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">on_trade</span>(<span class="params">self, trade: TradeData</span>):</span></span><br><span class="line">    print(trade)</span><br><span class="line">    <span class="comment"># 交易数据</span></span><br><span class="line">    <span class="keyword">if</span> trade.direction == Direction.LONG <span class="keyword">and</span> trade.offset == Offset.OPEN:</span><br><span class="line">        self.long_entry = trade.price  <span class="comment"># 做多的当前价格</span></span><br><span class="line">        self.trade_money = self.trade_money - \</span><br><span class="line">            (<span class="number">1</span> + trade_fee_rate) * trade.price * \</span><br><span class="line">            trade.volume - slippage * trade.volume  <span class="comment"># 当前剩余 USDT</span></span><br><span class="line">    <span class="keyword">elif</span> trade.direction == Direction.SHORT <span class="keyword">and</span> trade.offset == Offset.CLOSE:</span><br><span class="line">        self.short_entry = trade.price  <span class="comment"># 做空的价格</span></span><br><span class="line">        self.trade_money = self.trade_money + \</span><br><span class="line">            (<span class="number">1</span> - trade_fee_rate) * trade.price * trade.volume  <span class="comment"># 当前剩余 USDT</span></span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        print(<span class="string">&quot;该情况不应该出现&quot;</span>)</span><br><span class="line"></span><br><span class="line">    print(<span class="string">f&#x27;当前剩余 USDT：<span class="subst">&#123;self.trade_money&#125;</span>, TRX：<span class="subst">&#123;self.pos&#125;</span>&#x27;</span>)</span><br><span class="line">    print(<span class="string">&quot;\n&quot;</span>)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">on_order</span>(<span class="params">self, order: OrderData</span>):</span></span><br><span class="line">    <span class="comment"># 发单状态改变会推送数据过来</span></span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">super</span>().on_order(order)</span><br></pre></td></tr></table></figure>
<p>这样跑出来得到的结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line"></span><br><span class="line">Sell: 2021-06-16 18:30:00+08:06</span><br><span class="line">满仓，遇到死叉，将卖出 TRX：4607.149649061856</span><br><span class="line">发送卖出订单，订单 id: [&#39;BACKTESTING.242&#39;]</span><br><span class="line">------------------------------------------------------------------</span><br><span class="line">TradeData(gateway_name&#x3D;&#39;BACKTESTING&#39;, symbol&#x3D;&#39;TRX-USDT&#39;, exchange&#x3D;&lt;Exchange.OKEX: &#39;OKEX&#39;&gt;, orderid&#x3D;&#39;242&#39;, tradeid&#x3D;&#39;242&#39;, direction&#x3D;&lt;Direction.SHORT: &#39;空&#39;&gt;, offset&#x3D;&lt;Offset.CLOSE: &#39;平&#39;&gt;, price&#x3D;0.07115, volume&#x3D;4607.149649061856, datetime&#x3D;datetime.datetime(2021, 6, 16, 19, 0, tzinfo&#x3D;&lt;DstTzInfo &#39;Asia&#x2F;Shanghai&#39; LMT+8:06:00 STD&gt;))</span><br><span class="line">当前剩余 USDT：326.80660340656914, TRX：0.0</span><br><span class="line"></span><br><span class="line">...</span><br><span class="line"></span><br><span class="line">2021-06-22 10:16:32.224890	逐日盯市盈亏计算完成</span><br><span class="line">2021-06-22 10:16:32.224942	开始计算策略统计指标</span><br><span class="line">2021-06-22 10:16:32.235820	------------------------------</span><br><span class="line">2021-06-22 10:16:32.235838	首个交易日：	2020-12-21</span><br><span class="line">2021-06-22 10:16:32.235846	最后交易日：	2021-06-16</span><br><span class="line">2021-06-22 10:16:32.235851	总交易日：	178</span><br><span class="line">2021-06-22 10:16:32.235856	盈利交易日：	79</span><br><span class="line">2021-06-22 10:16:32.235861	亏损交易日：	82</span><br><span class="line">2021-06-22 10:16:32.235869	起始资金：	100.00</span><br><span class="line">2021-06-22 10:16:32.235876	结束资金：	326.81</span><br><span class="line">2021-06-22 10:16:32.235882	总收益率：	226.81%</span><br><span class="line">2021-06-22 10:16:32.235888	年化收益：	465.08%</span><br><span class="line">2021-06-22 10:16:32.235894	最大回撤: 	-54.06</span><br><span class="line">2021-06-22 10:16:32.235900	百分比最大回撤: -23.39%</span><br><span class="line">2021-06-22 10:16:32.235905	最长回撤天数: 	8</span><br><span class="line">2021-06-22 10:16:32.235911	总盈亏：	226.81</span><br><span class="line">2021-06-22 10:16:32.235916	总手续费：	42.99</span><br><span class="line">2021-06-22 10:16:32.235922	总滑点：	0.00</span><br><span class="line">2021-06-22 10:16:32.235927	总成交金额：	42,991.33</span><br><span class="line">2021-06-22 10:16:32.235933	总成交笔数：	242</span><br><span class="line">2021-06-22 10:16:32.235939	日均盈亏：	1.27</span><br><span class="line">2021-06-22 10:16:32.235945	日均手续费：	0.24</span><br><span class="line">2021-06-22 10:16:32.235950	日均滑点：	0.00</span><br><span class="line">2021-06-22 10:16:32.235955	日均成交金额：	241.52</span><br><span class="line">2021-06-22 10:16:32.235963	日均成交笔数：	1.3595505617977528</span><br><span class="line">2021-06-22 10:16:32.235968	日均收益率：	0.67%</span><br><span class="line">2021-06-22 10:16:32.235974	收益标准差：	5.28%</span><br><span class="line">2021-06-22 10:16:32.235980	Sharpe Ratio：	2.41</span><br><span class="line">2021-06-22 10:16:32.235985	收益回撤比：	9.70</span><br><span class="line">2021-06-22 10:16:32.236454	策略统计指标计算完成</span><br></pre></td></tr></table></figure>
<p>OK，这样结果差距就微乎其微了。</p>
<h3 id="结语"><a href="#结语" class="headerlink" title="结语"></a>结语</h3><p>这次问题的产生由于对滑点的不熟悉，所以并未加入到所持本金的计算当中，因而导致巨大的差异。探究<code>calculate_pnl</code>函数，才对收益的计算有所了解。</p>
<p>但现在仍然有对 <code>inverse</code>、<code>on_tick</code>，合约上的很多东西不明白，后面来慢慢搞懂和记录。</p>
 
      <!-- reward -->
      
      <div id="reword-out">
        <div id="reward-btn">
          打赏
        </div>
      </div>
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>版权声明： </strong>
          
          本博客所有文章除特别声明外，著作权归作者所有。转载请注明出处！
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=https://zesicus.gitee.io/2021/06/21/EMA%E7%AD%96%E7%95%A5%E5%9B%9E%E6%B5%8B%E9%97%AE%E9%A2%982020-06-21/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/VNPY/" rel="tag">VNPY</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2021/06/28/Linux-screen-%E4%BD%BF%E7%94%A8/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            Linux screen 基本使用
          
        </div>
      </a>
    
    
      <a href="/2020/02/03/iOS-app-%E9%87%8D%E7%AD%BE%E5%90%8D-iReSign/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">iOS app 重签名 iReSign</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "M5MxuHVy9KSi3HL3TynyJ7Wx-gzGzoHsz",
    app_key: "R1KGWG7s6ISWPXYKvbmjyNka",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
   
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2020-2021
        <i class="ri-heart-fill heart_icon"></i> Decline
      </li>
    </ul>
    <ul>
      <li>
        
        
        
        由 <a href="https://hexo.io" target="_blank">Hexo</a> 强力驱动
        <span class="division">|</span>
        主题 - <a href="https://github.com/Shen-Yu/hexo-theme-ayer" target="_blank">Ayer</a>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>访问人数:<span id="busuanzi_value_site_uv"></span></s>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>浏览次数:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://v1.cnzz.com/z_stat.php?id=1279621682&amp;web_id=1279621682'></script>
        
      </li>
    </ul>
  </div>
</footer>
      <div class="float_btns">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

      </div>
    </main>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/logoicon.png" alt="黑森林"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/friends">友链</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/about">关于我</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="搜索">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <script>
      if (window.matchMedia("(max-width: 768px)").matches) {
        document.querySelector('.content').classList.remove('on');
        document.querySelector('.sidebar').classList.remove('on');
      }
    </script>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="/images/ali.jpeg">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="/images/wx.png">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
    
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->


<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: 'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto'
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->

<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>

<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->


<link rel="stylesheet" href="/css/clipboard.css">

<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>


<!-- CanvasBackground -->


<script src="/js/dz.js"></script>



    
  </div>
</body>

</html>